(function(KKBus){

    function GiftsController() {
        var self = this;
        
        self.gifts = ko.observableArray();
        
        self.getGifts = function (page)
        {
            self.gifts.removeAll();
            
            app.request++;
        
            var url = 'rest/awards';
            
            if (page > 0) {
                
                
            }
        
        
        KKBus.Ajax.doGet(url, function(data, textStatus, jqXHR)
        {
           
        var jsData = JSON.parse(data);
        var i = jsData.length;
        
        
            while(i--){
                 self.gifts.push(new KKBus.GiftModel(jsData[i].id, jsData[i].name, jsData[i].description, jsData[i].points, jsData[i].quantity)); 
         }
         
         app.request--;
         
          if (app.request == 0) {
                    if (app.settings.DEBUG == true) { console.log("Load template from: " + GiftsController.name); }
                    setTimeout(function() { app.loadTemplate(); }, 1000);
                }
            });
        };
        
        self.showMessage = ko.observable(false);
        self.message = ko.observable("---");
        self.orderGift = function(id, index) {
            var gift = app.Knockout.GiftsController.gifts()[index];
            var quantity = gift.quantity();
            var points = gift.points();

            var user = app.Knockout.AuthenticationController.user;
            var userId = user.id();
            var userPoints = user.points();

            if (userPoints >= points && quantity > 0) {
                var exchange = JSON.stringify({
                    hash: "",
                    idAward: id,
                    idUser: userId
                });            

                KKBus.Ajax.doPost('rest/exchange', exchange, function(result, textStatus, jqXHR) {
                    if (result == "ADDED") {
                        gift.quantity(quantity - 1);
                        user.points(userPoints - points);
                        
                        self.message('Kod weryfikujący zamówienie został wysłany na twój e-mail!');
                        self.showMessage(true);
                        setTimeout(function() { 
                            self.message('---');
                            self.showMessage(false);
                        }, 5000);
                    }
                });
            } else {
                self.message('Nie posiadasz wystarczającej ilości punktów!');
                self.showMessage(true);
                setTimeout(function() { 
                    self.message('---');
                    self.showMessage(false);
                }, 5000);
            }
        }
        
    }
   

    KKBus.GiftsController = GiftsController;
    
}(window.KKBus));

